const wrapper = require('co-mysql'),
      mysql   = require('mysql'),
      dbCfg   = require('../config/db.cfg');

var pool = mysql.createPool(dbCfg),
    p    = wrapper(pool);

module.exports = {
    findAll() {
        return p.query('select * from sys_user');
    },
    findOne(id) {
        return p.query('select * from sys_user where ?', {id: id});
    },
    create(user) {
        user.state = true;
        user.updatime = Dates.now().getTime();
        return p.query('insert into sys_user set ?', user);
    },
    update(user) {
        user.updatime = Dates.now().getTime();
        return p.query('update sys_user set ? where id=?', [user, user.id]);
    },
    remove(id) {
        return p.query('update sys_user set ? where ?', [{state: false}, {id: id}]);
    },
    *login(username, password) {
        let user, users, result = Result.error('登录失败');
        users = yield p.query('select * from sys_user where ?', {code: username});
        if (users.length) {
            user = users[0];
            result.setSuccess('登录成功', user);
        }
        if(!user) {
            result.setError('无此用户');
        }
        return user;
    }
};